package com.cll.learn.queue;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2021/5/15 19:58
 */
public class MyBlockingQueue {
    /**
     * 队列容量
     */
    private final int capacity = 5;
    /**
     * 添加数据的位置
     */
    private int addIndex;

    /**
     * 取出数据的位置
     */
    private int getIndex;

    /**
     * 添加锁
     */
    private final byte[] addLock = new byte[0];
    /**
     * 取出锁
     */
    private final byte[] getLock = new byte[0];

    /**
     * 队列数据
     */
    private final int[] data = new int[capacity];

    /**
     * 当前队列中元素个数
     */
    private int count;

    public MyBlockingQueue() {
        this.addIndex = 0;
        this.getIndex = 0;
        this.count = 0;
    }

    public void add(int i) throws InterruptedException {
        System.out.println("===>>> 添加对象 = " + i);
        synchronized (addLock) {
            if (capacity == count) {
                System.out.println("===>>> 队列已满，需要等待取出");
                addLock.wait();
            }
        }
        System.out.println("===>>> 添加对象成功 = " + i);
        enQueue(i);
    }

    private void enQueue(int i){
        synchronized (getLock) {
            data[addIndex] = i;
            if ((++addIndex) == capacity) {
                addIndex = 0;
            }
            count++;
            getLock.notify();
        }

    }

    public Integer get() throws InterruptedException {
        System.out.println("===>>> 从队列取出消息");
        synchronized (getLock) {
            if (0 == count) {
                System.out.println("===>>> 队列消息为空，需要等待放入消息");
                getLock.wait();
            }
        }
        int i = deQueue();
        System.out.println("===>>> 取出消息成功 =" + i);
        return i;
    }

    private int deQueue(){
        synchronized (addLock) {
            int result = data[getIndex];
            if (++getIndex == capacity) {
                getIndex = 0;
            }
            count--;
            addLock.notify();
            return result;
        }
    }
}
